<?php
/**
 * Description: 收藏
 * Author: hezhizheng
 * Date: 2018/6/11
 * Time: 10:14
 * Created by Created by Panxsoft.
 */

namespace App\Http\Controllers\App;

use App\Exceptions\ApiErrCode;
use App\Http\Controllers\ApiController;
use App\Http\Requests\App\UserFavorsPollRequest;
use App\Http\Requests\App\UserFavorStoreRequest;
use App\Models\OpenWechat\ScanEvent;
use App\Models\OpenWechat\WechatUser;
use App\Models\OpenWechat\WechatUserFavor;
use App\Models\Store\Store;
use App\Services\Utils\Guard;
use App\Services\Utils\SimpleQrCode;
use Illuminate\Http\Response;

class WechatUserFavorsController extends ApiController
{
    const ROUTES = [
        'store' => 'api.app.user.favors.store',
        'poll'  => 'api.app.user.favors.poll',
    ];

    /**
     * 试妆图片的收藏，返回图片的链接
     * @test
     *
     * 用户扫码，有公众号，前端直接请求授权，再请求update()方法
     * @used-by \App\Http\Controllers\Wechat\V2_3\FavorController::update()
     *
     * 用户扫码，无公众号h5处理方法，前端请求 patchPhone()方法，填写手机号，之后跳到 update()方法
     * @used-by \App\Http\Controllers\Wechat\WechatUserController::patchPhone()
     * @used-by \App\Http\Controllers\Wechat\V2_3\FavorController::update()
     *
     * @param UserFavorStoreRequest $request
     *
     * @return array|\Illuminate\Contracts\Routing\ResponseFactory
     */
    public function store(UserFavorStoreRequest $request)
    {
        $store = Guard::deviceAccount()->store;
        $customer = Guard::deviceAccount()->customer;
        $device_account = Guard::deviceAccount();

        $wechat_user_favor = $this->storeWechatUserFavor($request, $store);

        $wechat_user_favor_id = $wechat_user_favor->id;
        $appid = $customer->authorizer->authorizer_appid ?? null;

        $scan_event = $this->storeScanEvent($store, $wechat_user_favor_id, $appid);
        $scan_event_id = $scan_event->id;

        $query_string = http_build_query([
            'scan_event_id' => $scan_event_id,
            'lang'          => $device_account->language,
            'customer_id'   => $customer->id,
            'store_id'      => $store->id,
            'favor_id'      => $wechat_user_favor_id,
            'appid'         => $appid,
        ]);

        $url = url(sprintf(WechatUser::WX_FAVOR_LOGIN_URL_FORMAT, $query_string));

        if ($request->type === 'png') return $this->responseImage(SimpleQrCode::toImage($url));

        return $this->response(compact('wechat_user_favor', 'url', 'scan_event_id'));
    }

    /**
     * 美妆镜生成用户收藏照片二维码后，Pad轮询判断用户是否扫码。
     * @test
     *
     * @param UserFavorsPollRequest $request
     * @return array|Response
     * @throws \Exception
     */
    public function userFavorsPoll(UserFavorsPollRequest $request)
    {
        /** @var ScanEvent $scan_event */
        $scan_event = ScanEvent::find($request->scan_event_id);
            $this->checkItemExist($scan_event, trans('app.scan_event_error'));
            $this->checkIsTrue(
                $scan_event->isScanned(), trans('app.check_can_operate'),
                ApiErrCode::APP_FAVORS_SCAN_EVT_NOT_FOUND
            );

        $message = trans('app.scavenging_state');

        return $this->response(compact('message'));
    }

    /**
     * @param UserFavorStoreRequest $request
     * @param Store $store
     * @return WechatUserFavor
     */
    private function storeWechatUserFavor(UserFavorStoreRequest $request, Store $store)
    {
        $create_data = [
            'product_ids'  => $request->product_ids ?: [],
            'store_id'     => $store->id,
            'try_on_photo' => $request->try_on_photo,
        ];

        return WechatUserFavor::create($create_data);
    }

    /**
     * @param Store $store
     * @param $wechat_user_favor_id
     * @param $appid
     * @return ScanEvent
     */
    private function storeScanEvent(Store $store, $wechat_user_favor_id, $appid)
    {
        $scan_event = ScanEvent::createNewEvent(
            ScanEvent::TYPE_PAD_USER_IMAGE,
            'WECHAT_USER_ID_PLACEHOLDER',
            [
                'store_admin_id'       => 0,
                'store_id'             => $store->id,
                'language'             => Guard::deviceAccount()->language,
                'customer_id'          => $store->customer_id,       // 无公众号的客户customer_id
                'wechat_user_favor_id' => $wechat_user_favor_id,
                'appid'                => $appid
            ]
        );

        return $scan_event;
    }
}